<template>
  <div>
    <!--  分隔   -->
    <el-row>
      <el-col :span="24"><div class="grid-content bg-purple-light">
        <div style="float: left; margin: 20px 100px; font-weight: 700;color:#606266;font-size: 20px"><i class="el-icon-search"></i>车辆查询</div>
      </div></el-col>
    </el-row>
    <!--  查询条件-->
    <el-form :inline="true" :model="queryForm" style="text-align: left; margin: 0 10%" ref="ruleForm">
      <el-form-item label="车牌号" prop="number">
        <el-input v-model="queryForm.number" placeholder="车牌号" clearable></el-input>
      </el-form-item>
      <el-form-item label="车辆类型" prop="type">
        <el-input v-model="queryForm.type" placeholder="车辆类型" clearable></el-input>
      </el-form-item>
      <el-form-item label="载重量" prop="minLoad">
        <el-input v-model="queryForm.minLoad" style="width: 60px" placeholder="最小"/>
      </el-form-item>
      <el-form-item label="~" prop="maxLoad">
        <el-input v-model="queryForm.maxLoad" style="width: 60px" placeholder="最大"/>
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="getList" plain>查询</el-button>
        <el-button type="info" @click="add()" plain>新增</el-button>
        <el-button type="info" @click="resetForm()" plain>重置</el-button>
      </el-form-item>
    </el-form>
    <!--  分隔行   -->
    <el-row>
      <el-col :span="24"><div class="grid-content bg-purple-light">
        <div style="float: left; margin: 0 100px; font-weight: 700;color:#606266;font-size: 20px"><i class="el-icon-s-unfold"></i>数据列表</div>
      </div></el-col>
    </el-row>
    <div id="s" class="animate__animated animate__zoomIn animate__delay-1s" style="margin-top: 20px">
    <!--  数据表格-->
    <el-table :default-sort="{prop: 'number', order: 'ascending'}" :data="tableData" stripe style="width: 100%" :border="true"
              :header-cell-style="{background:'#209e91', color:'#ffffff',textAlign:'center'}">
      <el-table-column
        label="序号"
        type="index"
        :index="indexAdd"
        width="50"
        align="center">
      </el-table-column>
      <el-table-column
        prop="number"
        label="车牌号"
        sortable
        width="250"
        align="center">
      </el-table-column>
      <el-table-column
        prop="type"
        label="车辆类型"
        width="200"
        align="center">
      </el-table-column>
      <el-table-column
        prop="baseDriver.driverName"
        label="关联司机"
        sortable
        width="250"
        align="center">
      </el-table-column>
      <el-table-column
        prop="carLoad"
        sortable
        label="载重量(吨)"
        width="250"
        align="center">
      </el-table-column>
      <el-table-column
        prop="volume"
        sortable
        label="容积(m³)"
        width="250"
        align="center">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center">
      </el-table-column>
      <el-table-column
        prop="modifyTime"
        label="修改时间"
        align="center">
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
        align="center">
        <template v-slot="scope">
          <el-button @click="detail(scope.row)" type="text" size="small" >详情</el-button>
          <el-button @click="edit(scope.row)" type="text" size="small">修改</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="remove(scope.row)">
            <el-button slot="reference" type="text" size="small">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
      <el-row>
        <el-col :span="24"><div class="grid-content bg-purple-light">
          <div style="margin: 20px"></div>
        </div></el-col>
      </el-row>
    <!--  分页-->
    <el-pagination
      @size-change="getList"
      @current-change="getList"
      :current-page.sync="queryForm.pageNum"
      :page-sizes="[10, 20, 30, 40, 60, 80, 100]"
      :page-size.sync="queryForm.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
      <el-row>
        <el-col :span="24"><div class="grid-content bg-purple-light">
          <div style="margin: 20px"></div>
        </div></el-col>
      </el-row>
    </div>
    <!--  新增/修改页面-->
    <el-dialog
      :title="title"
      :visible.sync="show"
      width="50%">
      <span>
        <el-form :model="form" :rules="rules" ref="ruleForm" label-width="80px">
          <el-form-item label="关联司机">
          <el-select v-model="form.baseDriver" placeholder="请选择" value-key="driverId" filterable>
            <el-option
              v-for="item in this.drivers"
              :key="item.driverId"
              :label="item.distinctName"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>

          <el-form-item label="车牌号" prop="number">
             <el-input :disabled="disableNumber" v-model="form.number"></el-input>
          </el-form-item>
          <el-form-item label="车辆类型">
          <el-select v-model="form.type" placeholder="请选择" filterable>
            <el-option
              v-for="item in this.carTypes"
              :key="item.id"
              :label="item.value"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
          <el-form-item label="长度(m)" prop="length">
             <el-input v-model="form.length"></el-input>
          </el-form-item>
          <el-form-item label="宽度(m)" prop="width">
             <el-input v-model="form.width"></el-input>
          </el-form-item>
          <el-form-item label="高度(m)" prop="height">
             <el-input v-model="form.height"></el-input>
          </el-form-item>
          <el-form-item label="容积(m³)" prop="volume">
             <el-input v-model="form.volume"></el-input>
          </el-form-item>
          <el-form-item label="载重量(吨)" prop="carLoad">
             <el-input v-model="form.carLoad"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="mark">
             <el-input v-model="form.mark"></el-input>
          </el-form-item>
          <el-form-item label="上传图片" ref="uploadElement" prop="imageUrl">
            <el-image v-for="ele in src" :src="ele"
                      style="width: 100px; height: 100px"
                      :preview-src-list="src"
                      :fit="'cover'"></el-image>
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="action"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :on-success="success"
              :on-exceed="handleExceed"
              :multiple="true"
              :on-change="handleChange"
              :file-list="fileList"
              list-type="picture"
              :limit="3"
              :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary" plain>选取图片</el-button>
              <!--              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload"-->
              <!--                         plain>上传图片</el-button>-->
              <div slot="tip" class="el-upload__tip">只能上传jpg文件，且不超过500KB</div>
            </el-upload>
        </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
    </div>

</template>

<script>

export default {

  name: "CarInfo",
  data() {
    //自定义数字校验
    var validateNumber = (rule, value, callback) => {

      if (!(/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value)) {
        callback(new Error('请输入数字值'))
      } else {
        callback()
      }
    }

    return {
      carTypes: [{
        id: '1',
        value: '厢式车'
      }, {
        id: '2',
        value: '卡车'
      }, {
        id: '3',
        value: '挂车'
      }],
      disableNumber: false,
      fileList: [],
      drivers: [],
      // showDriver: false,
      action: 'api/car/setHeadImg',
      //查询对象
      queryForm: {
        pageNum: 1,
        pageSize: 10
      },
      //表格数组
      tableData: [],

      //共多少条
      total: 0,
      //表单对象
      form: {driverId: '', baseDriver: {}},
      //显示新增、修改
      show: false,
      //标题
      title: '',
      //校验新增修改表单数据
      rules: {
        number: [
          {required: true, message: '请输入车牌号名称', trigger: 'blur'},
          //有bug：检验通过仍无法提交
          // {
          //   validator: (rule, value, callback) => {
          //     if (!this.checkPlateNumberFormat(value)) {
          //       console.log("in")
          //       callback('请输入正确的车牌号');
          //     }
          //   }, trigger: "blur"
          // },

        ],
        length: [
          {required: true, message: '请输入车辆长度', trigger: 'blur'},
          {validator: validateNumber, trigger: 'blur'},

        ],
        width: [
          {required: true, message: '请输入车辆宽度', trigger: 'blur'},
          {validator: validateNumber, trigger: 'blur'},

        ],
        height: [
          {required: true, message: '请输入车辆高度', trigger: 'blur'},
          {validator: validateNumber, trigger: 'blur'},

        ],
        volume: [
          {required: true, message: '请输入车辆容积', trigger: 'blur'},
          {validator: validateNumber, trigger: 'blur'},

        ],
        carLoad: [
          {required: true, message: '请输入车辆载重', trigger: 'blur'},
          {validator: validateNumber, trigger: 'blur'},

        ],
      }
    }
  },
  methods: {

    //跳转车辆详情页，携带车辆基本信息
    detail(row) {
      this.$store.commit('carDetail', row)
      this.$router.push('CarDetail')
    },

    indexAdd(index) {
      const page = this.queryForm.pageNum // 当前页码
      const pageSize = this.queryForm.pageSize // 每页条数
      return index + 1 + (page - 1) * pageSize
    },
    //搜索条件重置
    resetForm() {
      this.queryForm.number = ''
      this.queryForm.type = ''
      this.queryForm.minLoad = ''
      this.queryForm.maxLoad = ''
    },
    //获取所有车辆基本信息
    getList() {
      this.$axios({
        url: 'car/list',
        method: 'post',
        data: this.queryForm
      }).then(res => {
        if (res.data.success) {
          this.tableData = res.data.object.list;
          this.total = res.data.object.total;
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    //新增前预处理表单
    add() {
      this.disableNumber = false
      this.drivers = []
      //加载空闲司机
      this.loadAll()
      //设置标题
      this.title = '新增'
      //显示对话框
      this.show = true
      //清空表单
      this.form = {}
      //清空图片
      this.$store.commit('carBasePhotos', '')
      //清空校验结果
      this.$nextTick(() => {
        // this.$refs.tree.setCheckedKeys([]);
        this.$refs['ruleForm'].clearValidate();
      })
    },
    //编辑前预处理表单
    edit(row) {
      this.drivers = []
      //加载空闲司机
      this.loadAll()

      this.title = '修改'
      //清空表单
      this.form = {}
      //禁止修改车牌
      this.disableNumber = true
      //给form对象赋值
      this.form = Object.assign({}, row);

      //清空图片，并重新赋值
      this.$store.commit('carBasePhotos', '')
      this.getPhotosForEdit()
      //显示对话框
      this.show = true
      //清空校验结果
      this.$nextTick(() => {
        // this.$refs.tree.setCheckedKeys([]);
        this.$refs['ruleForm'].clearValidate();
      })
    },
    //回显修改时的图片
    getPhotosForEdit() {
      this.$axios({
        url: 'car/getCarAndDriver/' + this.form.id,
        method: 'post',
      }).then(res => {
        if (res.data.success) {
          this.$store.commit('carBasePhotos', res.data.object.photos)
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    //删除车辆信息
    remove(row) {
      this.$axios({
        url: 'car/remove/' + row.id,
        method: 'post'
      }).then(res => {
        if (res.data.success) {
          this.$message({
            message: res.data.message,
            type: 'success'
          });
          this.getList();
        } else {
          this.$message.error(res.data.message);
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    //提交添加修改的表单
    submit() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          //校验通过
          if (this.title == '新增') {
            this.$refs['ruleForm'].validate((valid) => {
              if (valid) {
                this.$axios({
                  url: 'car/add',
                  method: 'post',
                  data: this.form
                }).then(res => {
                  if (res.data.success) {
                    this.show = false;
                    //上传图片
                    this.submitUpload()
                    this.getList()
                    this.$message.success('上传成功');
                  } else {
                    this.$message.error(res.data.message);
                  }
                }).catch(err => {
                  this.$message.error(err.message);
                })
              }
            });
          } else {

            this.$axios({
              url: 'car/edit',
              method: 'post',
              data: this.form
            }).then(res => {
              if (res.data.success) {
                this.show = false;
                //上传图片
                this.submitUpload()
                this.getList()
                this.$message.success('上传成功');
              } else {
                this.$message.error(res.data.message);
              }
            }).catch(err => {
              this.$message.error(err.message);
            })
          }
        }
      });
    },
    //选择文件时注入fileList
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    handleExceed(file, fileList) {
      return this.$message.warning('最多上传3张')
    },
    //上传车辆图片
    submitUpload() {
      //判断是否有文件再上传
      // if (this.fileList.length === 0 && this.title == '新增') {
      //   return this.$message.warning('请选取文件后再上传')
      // }
      // 下面的代码将创建一个空的FormData对象:
      const formData = new FormData()
      // FormData.append文件数组到表单里面
      this.fileList.forEach((file) => {
        formData.append('file', file.raw)
      })
      // 添加其他的自定义参数到后端
      formData.append('car', this.form.number)
      this.$axios({
        url: 'car/setHeadImg',
        method: 'post',
        data: formData
      }).then(res => {
        if (res.data.success) {
          if (res.data.code == 200) {
            this.$store.commit('carBasePhotos', res.data.object)
          } else {
            this.$message.error('上传图片失败');
          }
          //清空fileList
          this.fileList = []
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt = file.size / 1024 / 1024 < 0.5;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt) {
        this.$message.error('上传头像图片大小不能超过 500KB!');
      }
      return isJPG && isLt;
    },
    success(res) {
      //用于上传回显本次上传信息(没用？)
      this.$store.commit('carBasePhotos', res.object)
      this.getList()
    },
    //加载所有未分配车的司机
    loadAll() {
      this.$axios({
        url: 'baseDriver/listAll',
        method: 'post',
        data: {}
      }).then(res => {
        if (res.data.success) {
          let allDrivers = res.data.object;
          for (let ele of allDrivers) {
            //防止司机姓名重复
            if (ele.status == '0') {
              ele.distinctName = ele.driverName + '(tel:' + ele.driverTel + ')'
              this.drivers.push(ele)
              console.log(this.drivers)
            }
          }
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    }
  },
  created() {
    this.getList()
  },
  // 上传多个图片后动态回显
  computed: {
    src() {
      const src = []
      if (this.$store.state.carBasePhotos != undefined) {
        for (const ele of this.$store.state.carBasePhotos) {
          src.push('data:image/jpeg;base64,' + ele)
          console.log(ele)
        }
      }
      return src;
    }
  },
}
</script>

<style scoped>
.el-select {
  width: 100%;
}
.el-button--info:hover {
  background: #209e91;
  border-color: #209e91;
  color: #FFF;
}
#s{
  width:90%;
  margin:10px auto;
  background-color: #ffffff;
  box-shadow: 10px 10px 5px #c4c6c7;
  border-radius: 5px
}
</style>
